#include"UdpClient.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include<iostream>
#include<cstdlib>
#include<string>
#include<cstring>
#include<netinet/in.h>
#include<arpa/inet.h>
#include"Common.hpp"
using namespace std;


//./client_udp 
int main(int argc,char* argv[])
{
    if(argc != 3)
    {
       cerr << "Usage:"<<argv[0] << "serverIp serverPort" << endl;
       Die(USAGE_ERR);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);//转成整数
    //1.创建套接字
    int sockfd = ::socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd < 0)
    {
       cerr << "socket error" << endl;
       Die(SOCKET_ERR);
    }
    //1.1 填充serve信息
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = ::inet_addr(serverip.c_str()); 

    //client dong 不断向服务器发消息
    while(true)
    {
      cout << "Please enter..." << endl;
      string message;
      getline(cin,message);
      
      //发给服务器需要知道服务器是谁 那就需要服务器的套接字信息
      int n = ::sendto(sockfd,message.c_str(),message.size(),0,CONV(&server),sizeof(server)); 
      //读取服务端相关消息
      struct sockaddr_in temp;
      socklen_t len = sizeof(temp);
      char buffer[1024];
      n = ::recvfrom(sockfd,buffer,sizeof(buffer)-1,0,CONV(&temp),&len);
      if(n > 0)
      {
         buffer[n] = 0 ;
         cout << buffer << endl;
      }
    }
    return 0;
}